package org.lboot.flow.loader.impl;

import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.lboot.core.auth.AuthService;
import org.lboot.flow.constant.FlowAssignConst;
import org.lboot.flow.loader.TaskUserLoader;
import org.lboot.flow.module.assign.FlowTaskAssign;
import org.lboot.rbac.module.dept.SysDept;
import org.lboot.rbac.module.dept.SysDeptService;
import org.lboot.rbac.module.role.SysRole;
import org.lboot.rbac.module.role.SysRoleService;
import org.lboot.rbac.module.user.SysUser;
import org.lboot.rbac.module.user.SysUserService;
import org.lboot.rbac.module.user.map.SysUserRoleService;
import org.springframework.data.domain.Example;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author kindear
 * 用户装载
 */
@Slf4j
@RequiredArgsConstructor
@AllArgsConstructor
public class DefaultTaskUserLoaderImpl implements TaskUserLoader {
    SysUserService userService;

    SysDeptService deptService;

    // SysRoleService roleService;

    SysUserRoleService userRoleService;

    @Override
    public List<String> load(List<FlowTaskAssign> assigns) {
        // 获取用户列表
        List<String> userIds = new ArrayList<>();
        for (FlowTaskAssign assign:assigns){
            String assignType = assign.getAssignType();
            String assignId = assign.getAssignId();
            // 用户直接加入
            if (assignType.equals(FlowAssignConst.USER)){
                userIds.add(assignId);
            }
            // 如果是角色
            if (assignType.equals(FlowAssignConst.ROLE)){
                List<SysUser> roleUsers = userRoleService.getUsers(Long.parseLong(assignId));
                // 提取 id 列表
                List<String> roleUserIds = roleUsers.stream().map(ele-> ele.getId().toString()).collect(Collectors.toList());
                // 加入
                userIds.addAll(roleUserIds);
            }
            // 如果是部门
            if (assignType.equals(FlowAssignConst.DEPT)){
                SysUser user = new SysUser();
                user.setDeptId(Long.parseLong(assignId));
                // 构建查询
                Example<SysUser> example = Example.of(user);
                List<SysUser> deptUsers = userService.getExample(example);
                // 提取id 列表
                List<String> deptUserIds = deptUsers.stream().map(ele-> ele.getId().toString()).collect(Collectors.toList());
                // 加入
                userIds.addAll(deptUserIds);
            }
        }
        return userIds;
    }
}
